package com.fingard.net;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.util.AESUtil;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.FGBiz;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.*;

/**
 * Created by F on 2019/7/25.
 */
public class FormSubmit {


    public static Map<String,String> fileUpload(String url,String actNum,String filepath,String subPath,String fileName,String charset){
        Map<String,String> resultMap = new HashMap<String, String>();
        try {
                CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                CloseableHttpResponse httpResponse = null;
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60*1000).setSocketTimeout(120*1000).build();
                HttpPost httpPost = new HttpPost(url);
                httpPost.addHeader("X-GW-APP-ID","1103");
                httpPost.addHeader("channel_id","CZ");
                httpPost.addHeader("x-gw-nonce",UUID.randomUUID().toString());
                httpPost.addHeader("x-gw-time",""+System.currentTimeMillis());
                httpPost.setConfig(requestConfig);
                MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                multipartEntityBuilder.addBinaryBody("file",new File(filepath));
                //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
                multipartEntityBuilder.addTextBody("actNum", actNum);
                multipartEntityBuilder.addTextBody("remotePath", subPath);
                multipartEntityBuilder.addTextBody("fileName", fileName);
                TreeMap<String, Object> treeMap = new TreeMap<String, Object>();
                treeMap.put("bytes", FileHelper.readFileBytes(filepath));
                treeMap.put("actNum", actNum);
                treeMap.put("remotePath", subPath);
                treeMap.put("sign", FGBiz.dspCenter.dspSet.encryptSecretKey);
                treeMap.put("fileName", fileName);
                multipartEntityBuilder.addTextBody("key", AESUtil.MD5Sign(JSON.toJSONString(treeMap)));
                HttpEntity httpEntity = multipartEntityBuilder.build();
                httpPost.setEntity(httpEntity);
               httpResponse = httpClient.execute(httpPost);
               int statusCode= httpResponse.getStatusLine().getStatusCode();
                if(statusCode== HttpStatus.SC_OK){
                HttpEntity httpEntityResp = httpResponse.getEntity();
                if(httpEntity!=null){
                    String result =converStreamToStr(httpEntityResp.getContent());
                    System.out.println("银行返回的报文："+result);
                    if(StringHelper.hasAnyChar(result)){
                        resultMap =(Map<String,String>) JSON.parse(result);
                        return resultMap;
                    }
                }else{
                    resultMap.put("respCode","-1");
                    resultMap.put("respInfo","没有收到响应内容");
                }
            }else{
                resultMap.put("respCode","-1");
                resultMap.put("respInfo","没有收到响应");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            resultMap.put("respCode","-1");
            resultMap.put("respInfo",ex.getMessage());
        }
        return resultMap;
    }

    public static String converStreamToStr(InputStream inputStream){
        BufferedReader bf=null;
        StringBuilder sb  =new StringBuilder();
        String readLine =null;
        try {
            bf =new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            while ((readLine=bf.readLine())!=null){
                sb.append(readLine+"\r\n");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }finally {
            try {
                inputStream.close();
                bf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return sb.toString();
    }

    public static String[] receiptInfoSend(String sendInfo, DirectBase directBase){
       return receiptInfoSend( sendInfo,  directBase, false);
    }
    public static String[] receiptInfoSend(String sendInfo, DirectBase directBase,boolean needTime){
    	return receiptInfoSend(FGBiz.dspCenter.dspSet.receiptPushServerUrl, sendInfo, directBase, needTime);
    }
    public static String[] receiptInfoSend(String pServerUrl, String sendInfo, DirectBase directBase,boolean needTime){
        String[] result =  new String[]{"",""};
        try {
            URL url = new URL(pServerUrl);
            if(FGBiz.dspCenter.dspSet.isEncryptReceiptData) {
                sendInfo = AESUtil.encrypt(sendInfo, FGBiz.dspCenter.dspSet.encryptSecretKey);
            }
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(60*1000);
            connection.setReadTimeout(180*1000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type","application/json;charset=UTF-8");
            connection.setRequestProperty("X-GW-APP-ID","1103");
            connection.setRequestProperty("channel_id","CZ");
            String uuid = UUID.randomUUID().toString();
            connection.setRequestProperty("X-GW-NONCE",uuid);
            connection.setRequestProperty("X-GW-TIME",System.currentTimeMillis()+"");
            connection.connect();
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            dataout.write(sendInfo.getBytes("UTF-8"));
            dataout.flush();
            dataout.close();

            BufferedReader bf =new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line =bf.readLine())!=null){
                sb.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();
            String jsonStr = sb.toString();
            if(directBase.sbLog==null){
                directBase.sbLog= new StringBuilder();
            }
            if(needTime) {
                directBase.sbLog.append(Format.DateTimeSSSFormat.format(new Date()));
            }
            directBase.sbLog.append( " 3.返回的报文：\r\n");
            directBase.sbLog.append(jsonStr);
            directBase.sbLog.append("\r\n\r\n");
            Map<String,String> map =(Map<String,String>) JSONObject.parse(jsonStr);
            if("0".equals(map.get("respCode"))){
                result[1] ="ok" ;
            }else{
                result[1] =map.get("respCode")+":"+map.get("respInfo");
            }
            return result;
        }catch (Exception ex){
            //ex.printStackTrace();
            result[0] = "exception";
            result[1] = LogHelper.getStackTrace(ex);
        }
        return result;
    }

    public static String[] receiptInfoSend(String pServerUrl, String sendInfo,StringBuilder pushLog){
        String[] result =  new String[]{"",""};
        try {
            URL url = new URL(pServerUrl);
            if(FGBiz.dspCenter.dspSet.isEncryptReceiptData) {
                sendInfo = AESUtil.encrypt(sendInfo, FGBiz.dspCenter.dspSet.encryptSecretKey);
            }
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(60*1000);
            connection.setReadTimeout(180*1000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type","application/json;charset=UTF-8");
            connection.setRequestProperty("X-GW-APP-ID","1103");
            connection.setRequestProperty("channel_id","CZ");
            String uuid = UUID.randomUUID().toString();
            connection.setRequestProperty("X-GW-NONCE",uuid);
            connection.setRequestProperty("X-GW-TIME",System.currentTimeMillis()+"");
            connection.connect();
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            dataout.write(sendInfo.getBytes("UTF-8"));
            dataout.flush();
            dataout.close();

            BufferedReader bf =new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line =bf.readLine())!=null){
                sb.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();
            String jsonStr = sb.toString();
            pushLog.append(Format.DateTimeSSSFormat.format(new Date()));
            pushLog.append( " 3.返回的报文：\r\n");
            pushLog.append(jsonStr);
            pushLog.append("\r\n\r\n");
            Map<String,String> map =(Map<String,String>) JSONObject.parse(jsonStr);
            if("0".equals(map.get("respCode"))){
                result[1] ="ok" ;
            }else{
                result[1] =map.get("respCode")+":"+map.get("respInfo");
            }
            return result;
        }catch (Exception ex){
            //ex.printStackTrace();
            result[0] = "exception";
            result[1] = LogHelper.getStackTrace(ex);
        }
        return result;
    }




    public static void main(String[] args) {
        String url ="http://221.136.68.106:20380/tmsSettle/api/receipt/receiptFileUpload";
        String actNum ="591902896710201";
        String localPath ="C:\\Users\\F\\Desktop\\CIB01";
        String subPath = "/201810/14/"+actNum;
        String fileName = "CIB01";
        Map<String,String> result = fileUpload(url,actNum,localPath,subPath,fileName,"utf-8");
        System.out.println(JSON.toJSONString(result));


    }
}
